<template>
  <el-upload
    :action="actionUrl"
    :accept="acceptType"
    :name="name"
    :disabled="disabled"
    :multiple="multiple"
    :auto-upload="autoUpload"
    :list-type="listType"
    :limit="limit"
    v-if="!readonly"
    :on-error="handleError"
    :on-success="handleChange"
    :headers="headers"
    class="el-upload-editor"
    :on-preview="filePreview"
    :file-list="fileList"
  >
    <el-button slot="default" size="small" type="primary" icon="el-icon-upload"
    >{{ defaultConfig.buttonText }}
    </el-button>
    <div slot="tip" class="el-upload__tip">{{ defaultConfig.uploadTip }}</div>
    <div
      v-if="listType === 'text'"
      class="el-upload-list__item is-success"
      slot="file"
      slot-scope="file"
    >
      <template>
        <a class="el-upload-list__item-name" @click="filePreview(file.file)"
        ><i :class="getIcoClass(file.file)"></i
        ><span style="margin-left: 8px;">{{ file.file.name }}</span>
        </a>
        <span class="download_btn" @click="download(file.file)">下载</span>
        <span @click="handleRemove(file.file)">
        <i class="el-icon-close"></i>
      </span>
      </template>
      <el-progress :percentage="file.file.progress" v-if="file.file.progress" class="progress"></el-progress>
    </div>
  </el-upload>
  <div v-else class="sz-common-upload-readonly">
    <ul class="el-upload-list el-upload-list--text" v-if="fileList.length > 0">
      <li
        v-for="item in fileList"
        tabindex="0"
        class="el-upload-list__item is-success"
        :style="{ backgroundColor: itemBg }"
      >
        <template>
          <a class="el-upload-list__item-name" @click="previewFile(item)"
          ><i :class="getIcoClass(item)"></i
          ><span style="margin-left: 8px;">{{ item.name }}</span>
          </a>
          <span class="download_btn" @click="download(item)">下载</span>
        </template>
        <el-progress :percentage="item.progress" v-if="item.progress" class="progress"></el-progress>
      </li>
    </ul>
    <div v-else-if="showEmpty" style="height: 40px;"></div>
  </div>
</template>

<script>
  import _ from "lodash";

  export default {
    name: "sz-common-upload",
    props: {
      config: {
        type: Object,
        default: function () {
          return {};
        }
      },
      action: {
        type: String,
        default: window.api.sysUploadUrl
      },
      accept: {
        type: String,
        default: ""
      },
      // 只读属性
      readonly: {
        type: Boolean,
        default: false
      },
      // 是否显示空布局
      showEmpty: {
        type: Boolean,
        default: false
      },
      // 默认值
      value: {
        type: String,
        default: function () {
          return "";
        }
      },
      name: {
        type: String,
        default: "file"
      },
      // 文件列表item背景色
      itemBg: {
        type: String,
        default: "#e0eef9"
      },
      limit: {
        type: Number,
        default: 100
      },
      disabled: {
        type: Boolean,
        default: false
      },
      multiple: {
        type: Boolean,
        default: false
      },
      // 业务编码 null 使用页面属性的配置，否则根据key查询相应的配置
      businessKey: {
        type: String,
        default: null
      },
      "auto-upload": {
        type: Boolean,
        default: true
      },
      "list-type": {
        type: String,
        default: "text"
      },
      // 上传路径参数
      path: {
        type: String,
        default: "workflow"
      }
    },
    data() {
      return {
        actionUrl: this.action + "?path=" + this.path,
        headers: {
          token: window.sessionStorage.getItem("token"),
          userRole: "ADMIN"
        },
        defaultConfig: {
          buttonText: "上传",
          uploadTip: "只能上传jpg/png文件，且不超过500kb"
        },
        acceptType: _.clone(this.accept),
        fileList: []
      };
    },
    watch: {
      value(val) {
        if (val) {
          console.log(val, "12");
          let tem = JSON.parse(val);
          this.fileList = [];
          tem.map(item => {
            this.fileList.push({name: item.fileName, url: item.id});
          });
        }
      }
    },
    mounted() {
      Object.assign(this.defaultConfig, this.config);
      if (this.value) {
        let tem = JSON.parse(this.value);
        console.log(tem, 1111);
        this.fileList = [];
        tem.map(item => {
          this.fileList.push({name: item.fileName, url: item.id});
        });
      } else {
        this.fileList = [];
      }
      if (this.businessKey){
        this.getSettingByKey()
      }
    },
    methods: {
      getIcoClass(item) {
        let type = item.name.split(".")[1];
        switch (type) {
          case "doc":
          case "docx":
            return "fa fa-file-word-o doc_blue";
            break;
          case "pdf":
            return "fa fa-file-pdf-o pdf_red";
            break;
          case "png":
          case "jpg":
            return "fa fa-file-image-o image_green";
            break;
          default:
            return "fa fa-file-text-o image_green";
            break;
        }
      },
      handleError(err, file, fileList) {
        this.$notify.error({
          title: "错误",
          dangerouslyUseHTMLString: true,
          duration: 2000,
          message: `<p style="display: block;width: 260px; word-wrap: break-word">${
            JSON.parse(err.message).message
            }</p>`
        });
      },
      /**
      * 描述：根据业务获取模块的上传类型和提示
      * 时间： 2021/3/22
      */
      getSettingByKey() {
        this.API.getModuleSettingByKey({key: this.businessKey}).then(res => {
          this.acceptType = '';
          if (res.data.fileTypes) {
            this.actionUrl =this.action + "?path=" + this.path +`&fileTypes=${res.data.fileTypes}`
            let arr = res.data.fileTypes.split(',');
            let nextArr = arr.map(item => {
              return "." + item
            })
            this.acceptType = nextArr.join(',')
          }
          this.defaultConfig.uploadTip = res.data.description ? res.data.description : ''
        })
      },

      // 移除文件
      handleRemove(file) {
        let index = this.fileList.findIndex((item, index, arr) => {
          return item.url == file.url;
        });
        this.fileList.splice(index, 1);
        let tem = [];
        if (this.fileList) {
          this.fileList.map(item => {
            if (item.response) {
              tem.push(item.response);
            } else if (item.url) {
              tem.push({
                fileName: item.name,
                id: item.url
              });
            }
          });
        }
        this.$emit("input", JSON.stringify(tem));
      },
      // 下载
      download(item) {
        // 已开始下载，不允许再次点击
        if (item.progress) {
          return
        }
        let fileDownload = require("js-file-download");
        let para = {id: item.url};
        this.ExportApi.getFile(para, ((evt) => {
          let percentage = Math.floor((evt.loaded / evt.total) * 100)
          if (item.progress) {
            item.progress = percentage
          } else {
            this.$set(item, "progress", percentage)
          }
          if (percentage === 100) {
            delete item.progress
          }
        }))
          .then(res => {
            const disposition = res.headers["content-disposition"];
            let fileName = this.getFileName(disposition);
            fileDownload(res.data, fileName);
          })
          .finally(() => {
          });
      },
      previewFile(item) {
        this.openTabPage(
          window.api.preFile +
          "?url=" +
          window.api.secretFilePreview +
          item.url +
          "?token=" +
          window.sessionStorage.getItem("token")
        );
      },
      handleChange(response, file, fileList) {
        let tem = [];
        this.fileList = [];
        if (fileList) {
          fileList.map(item => {
            if (item.response) {
              tem.push(item.response);
              this.fileList.push({
                name: item.response.fileName,
                url: item.response.id
              });
            } else if (item.url) {
              tem.push({
                fileName: item.name,
                id: item.url
              });
              this.fileList.push({name: item.name, url: item.url});
            }
          });
        }
        console.log(response, file, fileList);
        this.$emit("input", JSON.stringify(tem));
      },
      // 文件预览 text,pdf,txt,其他格式下载
      filePreview(file) {
        console.log(file, "");
        if (file.url) {
          this.openTabPage(
            window.api.preFile +
            "?url=" +
            window.api.secretFilePreview +
            file.url +
            "?token=" +
            window.sessionStorage.getItem("token")
          );
        } else {
          if (file.response) {
            this.openTabPage(
              window.api.preFile +
              "?url=" +
              window.api.secretFilePreview +
              file.response.id +
              "?token=" +
              window.sessionStorage.getItem("token")
            );
          }
        }
      }
    }
  };
</script>

<style lang="less" scoped>
  .el-upload-editor {
    .el-upload-list__item {
      margin-top: 0px;
      background-color: #ffffff;
      border-radius: 10px;
      display: flex;
    }

    .el-upload-list__item-name {
      margin-right: 0px;
      font-size: 14px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      line-height: 29px;
      color: #303030;
      opacity: 1;
    }

    .download_btn {
      color: #0075ff;
      padding-left: 20px;
      line-height: 29px;
      cursor: pointer;
      margin-right: 20px;
      width: 60px;
      min-width: 50px;
    }
  }

  .sz-common-upload-readonly {
    .el-upload-list {
      display: flex;
      flex-wrap: wrap;
    }

    .download_btn {
      color: #0075ff;
      padding-left: 20px;
      line-height: 29px;
      cursor: pointer;
      width: 60px;
    }

    .el-upload-list__item {
      margin-bottom: 20px !important;
      margin-top: 0px;
      background-color: #e0eef9;
      padding: 16px 12px;
      border-radius: 10px;
      display: flex;
      justify-content: space-between;
    }

    .el-upload-list__item-name {
      margin-right: 0px;
    }
  }
</style>
